#include "srv_head.h"

int main (int argc, char * argv [])
{	
	if (argc != 2) {
	printf("输入格式错误，eg: ./2_ip + vm 的网络ip\n");
	return 1;
	}
	int ser_fd,cli_fd;
	struct sockaddr_in ser_addr,cli_addr;
	socklen_t ser_len,cli_len; 
	int ret;//参数返回值
	char Cmd[50]; //客户端的指令
	//1.买电话
	ser_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (ser_fd== -1) {
		perror("socket");
		exit(1);
	} 
	//防止端口
	int on=1;
	setsockopt(ser_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	bzero(&ser_addr, sizeof(ser_addr));
	ser_addr.sin_family = AF_INET;
	ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);//绑定本机的所有IP
	//ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
	ser_addr.sin_port = htons(12345);
	ser_len = sizeof(ser_addr);
		
	ret=bind(ser_fd, (struct sockaddr *)&ser_addr, ser_len);
	if(ret<0){
		perror("bind fail");
		return -1;
	}

	ret = listen(ser_fd, 5);
	if(ret == -1){
	printf("连接客户端失败\n");
	exit(1);
	}
	bzero(&cli_addr, sizeof(cli_addr));
	cli_len=sizeof(cli_addr);
	while(1){
	printf("等待客户端的指令..................\n");
	cli_fd=accept(ser_fd, (struct sockaddr *)&cli_addr, &cli_len);	//产生分机
	if(cli_fd == -1){
		printf("分机失败\n");
		exit(1);
	}
	ret = read(cli_fd,Cmd,N);//读取客户端发送的数据
	if(ret < 0){
		printf("文件读取失败\n");
		exit(1);
	}
	printf("recv cmd: %s\n",Cmd);	
	printf("接收到的指令是：%s\n",Cmd);
	//比较函数 
	if(strncmp(Cmd,"ls",2)==0){
		do_cli_ls(cli_fd);
	}else if(strncmp(Cmd,"get",3)==0){
		do_cli_get(cli_fd,Cmd + 4);//过滤掉 get 四个字节 提取文件名
	}else if(strncmp(Cmd,"put",3)==0){
		do_cli_put(cli_fd, Cmd + 4);
	}else{	
		printf("服务端指令:%s未存在\n",Cmd);
	}
	
	
	}
	

	return 0;

}


